# encoding=utf-8
import os
import sqlite3
import time

from PySide6 import QtCore
from watchdog.observers import Observer
from watchdog.events import LoggingEventHandler

from src.utils.logger import Logger
from src.utils.hoi_file_parser import HoiParser
from src.service import save_node_service

logger = Logger(__name__)


class IronManFileEventHandler(LoggingEventHandler):
    __slots__ = ["_signal"]

    def __init__(self, signal: QtCore.Signal):
        super(IronManFileEventHandler, self).__init__()
        self._signal = signal

    def on_created(self, event):
        logger.i(1111)

    def on_deleted(self, event):
        logger.i(22222)

    def on_moved(self, event):
        """
        监听.hoi文件，根据文件内容判断是不是iron man 铁人模式文件
        :param event:
        :return:
        """
        super(LoggingEventHandler, self).on_created(event)
        logger.i(event.src_path)
        logger.i(event.dest_path)
        hoi = HoiParser.parse(file_path=event.dest_path)
        last_hoi = save_node_service.last_node(hoi.src_path)
        if last_hoi.date == hoi.date:
            logger.i("文件已存档，无须保存")
        else:
            hoi.parent = last_hoi.id
            HoiParser.save(hoi)
            try:
                save_node_service.insert_node(hoi)
                self._signal.emit()
            except sqlite3.IntegrityError as e:
                logger.i("文件已存档，无须保存")


class IronManListening:
    __slots__ = ["_path", "_event_handler", "_observer"]

    def __init__(self, listen_path: str, signal: QtCore.Signal):
        self._path = listen_path
        self._event_handler = IronManFileEventHandler(signal)

        self._observer = Observer()

        # 注册事件处理器，配置监控目录
        self._observer.schedule(self._event_handler, self._path, recursive=True)

    def start(self):
        self._observer.start()

    def join(self):
        self._observer.join()

    def stop(self):
        self._observer.stop()

    def set_daemon(self, b=True):
        self._observer.setDaemon(b)


if __name__ == '__main__':
    # demo
    path = os.path.expanduser("~")
    path = os.path.join(path, r"Documents\Paradox Interactive\Hearts of Iron IV\save games")

    i = IronManListening(path)
    i.start()

    # 为了保证主线程运行
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        i.stop()

    i.join()
